import { LockOutlined, SafetyCertificateOutlined, UserOutlined } from '@ant-design/icons';
import { Alert, Col, message, Row } from 'antd';
import React, { useState } from 'react';
import { ProFormText, LoginForm } from '@ant-design/pro-form';
import { history, useModel } from 'umi';
import Footer from '@/components/Footer'; // import { login, getCaptcha } from '@/services/ant-design-pro/api';

import styles from './index.less';
import { randomNum } from '@/utils';
import { login } from '@/services/ant-design-pro/api';
import { setUserToken, setUserId } from '@/utils/cache';

const LoginMessage: React.FC<{
    content: string;
}> = ({ content }) => (
    <Alert
        style={{
            marginBottom: 24,
        }}
        message={content}
        type="error"
        showIcon
    />
);

const Login: React.FC = () => {
    const [userLoginState, setUserLoginState] = useState<API.LoginResult>({});
    const { initialState, setInitialState } = useModel('@@initialState');
    const num: string = randomNum(1000000, 9999999);
    const [captcha, setCaptcha] = useState('/api/common/captcha/' + num);
    const [codeNum, setCodeNum] = useState(num);

    const getCodeUrl = () => {
        const code = randomNum(1000000, 9999999);
        setCodeNum(code);
        setCaptcha('/api/common/captcha/' + code);
        return '/api/common/captcha/' + code;
    };

    const fetchUserInfo = async () => {
        const userInfo = await initialState?.fetchUserInfo?.();

        if (userInfo) {
            await setInitialState((s) => ({ ...s, currentUser: userInfo }));
        }
    };

    const handleSubmit = async (values: API.LoginParams) => {
        try {
            // 登录
            const param: any = { ...values };
            param.number = codeNum;
            const msg = await login(param);

            if (msg) {
                // 添加缓存
                setUserId(msg.user_id);
                setUserToken(msg.token);

                const defaultLoginSuccessMessage = '登录成功！';
                message.success(defaultLoginSuccessMessage);
                await fetchUserInfo();
                /** 此方法会跳转到 redirect 参数所在的位置 */

                if (!history) return;
                const { query } = history.location;
                let { redirect } = query as {
                    redirect: string;
                };
                if (redirect && redirect.includes('/user/login')) {
                    redirect = '/'
                }
                history.push(redirect || '/');
                return;
            } // 如果失败去设置用户错误信息

            setUserLoginState(msg);
        } catch (error) {
            console.log('error', error);
            // const defaultLoginFailureMessage = '登录失败，请重试！';
            // message.error(defaultLoginFailureMessage);
        }
    };

    const { status } = userLoginState;
    return (
        <div className={styles.container}>
            <div className={styles.content}>
                <LoginForm // logo={<img alt="logo" src="/logo.svg" />}
                    title="管理后台"
                    // subTitle={'管理后台'}
                    initialValues={{
                        autoLogin: true,
                    }} // actions={[
                    //   <FormattedMessage
                    //     key="loginWith"
                    //     id="pages.login.loginWith"
                    //     defaultMessage="其他登录方式"
                    //   />,
                    //   <AlipayCircleOutlined key="AlipayCircleOutlined" className={styles.icon} />,
                    //   <TaobaoCircleOutlined key="TaobaoCircleOutlined" className={styles.icon} />,
                    //   <WeiboCircleOutlined key="WeiboCircleOutlined" className={styles.icon} />,
                    // ]}
                    onFinish={async (values) => {
                        await handleSubmit(values as API.LoginParams);
                    }}
                >
                    {/* <Tabs activeKey={type} onChange={setType}> */}
                    {/* <Tabs.TabPane
             key="account"
             tab={intl.formatMessage({
               id: 'pages.login.accountLogin.tab',
               defaultMessage: '账户密码登录',
             })}
           />
           <Tabs.TabPane
             key="mobile"
             tab={intl.formatMessage({
               id: 'pages.login.phoneLogin.tab',
               defaultMessage: '手机号登录',
             })}
           />
          </Tabs> */}

                    {status === 'error' && <LoginMessage content={'错误的用户名和密码(admin/ant.design)'} />}
                    <ProFormText
                        name="username"
                        fieldProps={{
                            size: 'large',
                            prefix: <UserOutlined className={styles.prefixIcon} />,
                        }}
                        placeholder={'请输入用户名'}
                        rules={[
                            {
                                required: true,
                                message: '用户名是必填项！',
                            },
                        ]}
                    />
                    <ProFormText.Password
                        name="password"
                        fieldProps={{
                            size: 'large',
                            prefix: <LockOutlined className={styles.prefixIcon} />,
                        }}
                        placeholder={'请输入密码'}
                        rules={[
                            {
                                required: true,
                                message: '密码是必填项！',
                            },
                        ]}
                    />
                    <Row>
                        <Col span={17}>
                            <ProFormText
                                name="verifyCode"
                                fieldProps={{
                                    size: 'large',
                                    prefix: <SafetyCertificateOutlined />,
                                    maxLength: 4
                                }}
                                placeholder={'请输入验证码！'}
                                rules={[
                                    {
                                        required: true,
                                        message: '验证码是必填项！',
                                    },
                                    {
                                        len: 4,
                                        message: '验证码长度为 4 位',
                                    },
                                ]}
                            />
                        </Col>
                        <Col span={7}>
                            <img onClick={getCodeUrl} src={captcha} />
                        </Col>
                    </Row>
                    <div
                        style={{
                            marginBottom: 24,
                        }}
                    >
                        {/* <ProFormCheckbox noStyle name="autoLogin">
             <FormattedMessage id="pages.login.rememberMe" defaultMessage="自动登录" />
            </ProFormCheckbox>
            <a
             style={{
               float: 'right',
             }}
            >
             <FormattedMessage id="pages.login.forgotPassword" defaultMessage="忘记密码" />
            </a> */}
                    </div>
                </LoginForm>
            </div>
            <Footer />
        </div>
    );
};

export default Login; // function path(path: any) {
//   throw new Error('Function not implemented.');
// }
